import { router, addRoutes } from "@/router";
import { getToken } from "@/composables/auth";
import { toast, showFullLoading, hideFullLoading } from "@/composables/util";
import store from "./store";

//全局前置守卫
let hasGetInfo = false;
router.beforeEach(async (to, from, next) => {
  //显示loading
  showFullLoading();

  const token = getToken();
  //如果没有登录或者即将到达的页面不是登录页--回到登录页
  if (!token && to.path != "/login") {
    toast("请先登录", "error");
    return next({ path: "/login" });
  }

  //防止重复登陆
  if (token && to.path == "/login") {
    toast("请勿重复登录", "error");
    return next({ path: from.path ? from.path : "/" });
  }

  //如果用户登录了，就自动获取用户信息，并存储在vuex当中
  let hasNewRoutes = false; //是否添加了新路由
  if (token && !hasGetInfo) {
    //调用action获取用户信息和菜单权限
    let { menus } = await store.dispatch("getinfoApi");
    hasGetInfo = true;
    //根据菜单动态添加路由
    hasNewRoutes = addRoutes(menus);
  }

  //设置页面标题
  let title = (to.meta.title ? to.meta.title : "") + "--子然";
  document.title = title;

  //如果添加了新路由--重新导航到目标路径否则就正常放行
  hasNewRoutes ? next(to.fullPath) : next();
});

//全局后置守卫
router.afterEach((to, from) => hideFullLoading());
